package com.aispeech.asr.apis.ssc.websocket.connection;


import java.util.HashMap;
import java.util.Map;

import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.NettyDataBuffer;

import lombok.Data;
import lombok.Getter;
import lombok.ToString;
import lombok.experimental.Accessors;

@ToString
@Data
@Accessors(chain = true)
public class Message {
    private String emitterId;
    private String message;
    private DataBuffer buffer;
    private String alignmentKey;
    @Getter
    private Map<String, Long> metrics;
    
    public static Message of(String emitterId, String receivedMessage, DataBuffer buffer) {
    	Message message = new Message();
    	
    	message.emitterId = emitterId;
    	message.message = receivedMessage;
    	
    	if(buffer != null) {
    		message.buffer = DateBufferFactory.getInstance().allocateBuffer();
    		NettyDataBuffer writeDataBuffer = DateBufferFactory.getInstance().wrap(buffer.asByteBuffer());
    		message.buffer.write(writeDataBuffer);	
			writeDataBuffer.release();
    	}
    		
    	return message;
    }
    
    public static Message alignment(String emitterId, String receivedMessage, String alignmentKey) {
    	Message message = new Message();
    	
    	message.emitterId = emitterId;
    	message.message = receivedMessage;
    	message.alignmentKey = alignmentKey;
    	return message;

    }
    
    public void addMetrics(String key, long value) {
    	if (metrics == null) {
    		metrics = new HashMap<String, Long>();
    	}
    	metrics.put(key, value);
    }
    
    public void addAllMetrics(Map<String, Long> addMetrics) {
    	if (metrics == null) {
    		metrics = new HashMap<String, Long>();
    	}
    	metrics.putAll(addMetrics);
    }
}
